package dataformat

import (
	"regexp"
	"strings"
)

const (
	fqdnRegexStrictPattern      = `^([a-zA-Z0-9]{1}([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)(\.[a-zA-Z0-9]{1}([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*?(\.[a-zA-Z]{1}[a-zA-Z0-9]{1,62})\.?$` // same as hostnameRegexStringRFC1123 but must contain a non numerical TLD (possibly ending with '.')
	dnsResolverAddrRegexPattern = `^(udp://)?([a-zA-Z0-9.-]+|([0-9]{1,3}\.){3}[0-9]{1,3})(:[0-9]+)?$`
)

var (
	fqdnRegexCompiled            = regexp.MustCompile(fqdnRegexStrictPattern)
	dnsResolverAddrRegexCompiled = regexp.MustCompile(dnsResolverAddrRegexPattern)
)

func IsFqdn(fqdnStr string) bool {
	if len(fqdnStr) > 255 {
		return false
	}

	return fqdnRegexCompiled.MatchString(fqdnStr)
}

func IsWildcardFqdn(fqdnStr string) bool {
	if len(fqdnStr) > 255 {
		return false
	}

	if !strings.HasPrefix(fqdnStr, "*.") {
		return false
	}

	fqdnStr = strings.TrimPrefix(fqdnStr, "*.")
	return fqdnRegexCompiled.MatchString(fqdnStr)
}

func IsDNSResolverAddress(address string) bool {
	if len(address) > 255 {
		return false
	}

	return dnsResolverAddrRegexCompiled.MatchString(address)
}
